package cn.itcast.wanxinp2p.account.service;

import cn.itcast.wanxinp2p.common.domain.BusinessException;
import cn.itcast.wanxinp2p.common.domain.CommonErrorCode;
import cn.itcast.wanxinp2p.common.domain.RestResponse;
import cn.itcast.wanxinp2p.common.util.OkHttpUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: Liu
 * @date: 2022/03/25
 * @time: 12:19
 */
@Service
public class SmsService {

    @Value("${sms.url}")
    private String smsURL;

    @Value("${sms.enable}")
    private Boolean smsEnable;

    public void verifySmsCode(String key, String code) {
        if (smsEnable) {
            //http://localhost:56085/sailing/verify?name=sms&verificationKey=xxx&verificationCode=xxx
            StringBuilder url = new StringBuilder(smsURL);
            url.append("verify?name=sms").append("&verificationKey=").append(key).append("&verificationCode=").append(code);
            RestResponse restResponse = OkHttpUtil.post(url.toString(), "");
            if (restResponse.getCode() != CommonErrorCode.SUCCESS.getCode()
                    || restResponse.getResult().toString().equalsIgnoreCase("false")) {
                //抛一个自定义异常
                throw new BusinessException(CommonErrorCode.E_100102);
            }
        }
    }

    public RestResponse getSmsMessageCode(String mobile) {
        if (smsEnable) {
            StringBuilder builder = new StringBuilder(smsURL);
            StringBuilder url = builder.append("generate?effectiveTime=300&name=sms");
            Map<String, String> paramMap = new HashMap<>(1);
            paramMap.put("mobile", mobile);
            String paramJson = JSON.toJSONString(paramMap);
            RestResponse restResponse = OkHttpUtil.post(url.toString(), paramJson);
            return restResponse;
        } else {
            return RestResponse.success();
        }

    }
}
